define(["angularAMD"], function (angularAMD) {
    angularAMD.service('B0204Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog','$mddProvider', '$calculater',
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $mddProvider, $calculater){
            this.init = function(machine,plot,type, feedback){

                var machine_no;
                var tmpLotNo;
                var tmpQty;
                var materialsInfo = [];
                var showFlag = true;

                if(type=='line'){
                    machine_no = machine.area_no;
                }else{
                    machine_no = machine.machine_no;
                }

                function checkMaterialDouble(materials_lot_no, materialsInfoList){
                    var isDouble = false;
                    if(materialsInfoList && materialsInfoList.length > 0){
                        materialsInfoList.forEach(function(materials){
                            if(materials.materials_lot_no == materials_lot_no){
                                isDouble = true;
                            }
                        });
                    }
                    return isDouble;
                }

                function barcodeScan(event, dialog){
                    if(event.keyCode == 13){
                        sub_release_part_info_get(dialog);
                    }
                }

                function sub_release_part_info_get(dialog){
                    var content={ //物料子資訊
                        wo_no:dialog.wo_no,
                        release_part_no:dialog.tmpPageCode.page_no,
                        return_type:'0', //發料單號
                        op_no: dialog.op_no
                    };

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_MAT.sub_release_part_info_get',
                        content : content,
                        success : function(data){
                            dialog.materialsInfo = data.sub_release_part_info_get;
                            if (showFlag) {
                                dialog.materialsInfo.forEach(item => {
                                    item.inputLotNo = '';
                                    item.qty = '0';
                                });
                            }
                            // 預設全選
                            dialog.selectAll(true);
                        }
                    });
                }
                var openDialog = function () {
                    $mddProvider.UseForm('B0204', () =>{
                        $mdDialog.dialog(
                            'module/moduleB/program/B02/B0204/B0204.html',
                            function(dialog){
                                return {
                                    css_url:'JSplugins/angular-material-lite/template/dynamicService.tmp.css',
                                    wo_no: plot.wo_no,
                                    machine_no:machine_no,
                                    op_no:plot.op_no,
                                    tmpPageCode : {page_no:''},
                                    tmpLotNo : tmpLotNo,
                                    tmpQty : tmpQty,
                                    show_flag: showFlag, // 20210107 add FOR #78842
                                    materialsInfo:materialsInfo,
                                    barcodeScan:barcodeScan,
                                    _isSelectAll: false, // 全選
                                    loadMaterialCodeList: function () { //查詢發料單號
                                        $MMWService.showQueryListPNIG({
                                            form_name: 'PageNo_52',
                                            condition: [
                                                {name:$filter('translate')('B0204.queryList.column2'), column_name:'MaterialInNo', query_mode:'2', value:dialog.tmpPageCode.page_no}
                                            ],
                                            header: [
                                                {label:$filter('translate')('B0204.queryList.column2'), code:'page_no'},
                                                {label:$filter('translate')('B0204.queryList.column3'), code:'page_name'}
                                            ],
                                            setCondition:function(conditions){
                                                if(dialog.wo_no != '')
                                                    conditions.push(
                                                        {column_name:'A.MONo', query_mode:'0', value: dialog.wo_no, merge_condition_model: 'AND'},
                                                        {column_name:'C.OpNo', query_mode:'0', value: dialog.op_no, merge_condition_model: 'AND'}
                                                    );
                                                return conditions;
                                            },
                                            confirm : function(selectItem){
                                                dialog.tmpPageCode = selectItem;
                                                sub_release_part_info_get(dialog);
                                            }
                                        });
                                    },
                                    addMaterials : function(){
                                        if(!dialog.tmpLotNo){
                                            $rootScope.showAlert($filter('translate')('B0204.showAlert.column1'));
                                        }else if(dialog.tmpQty==0 || dialog.tmpQty==''|| dialog.tmpQty==undefined){
                                            $rootScope.showAlert($filter('translate')('B0204.showAlert.column5',{
                                                materials_lot_no: dialog.tmpLotNo
                                            }),function(){
                                                dialog.tmpQty='';
                                            });
                                        }else{
                                            // 20210111 add FOR #78842
                                            if(dialog.show_flag){
                                                // 检查物料批号列表中是否存在
                                                var tempList = dialog.materialsInfo.filter(item=> item.materials_lot_no == dialog.tmpLotNo);
                                                if(tempList.length > 0 ){
                                                        dialog.materialsInfo.forEach(item => {
                                                            if(item.materials_lot_no == dialog.tmpLotNo){
                                                                item.inputLotNo = dialog.tmpLotNo;
                                                                item.qty = String($calculater.decimalAdd(Number(dialog.tmpQty),Number(item.qty)));
                                                            }
                                                        });
                                                }else{
                                                        $rootScope.showAlert($filter('translate')('B0204.showAlert.column6',{
                                                            materials_lot_no: dialog.tmpLotNo
                                                        }));
                                                }
                                            } else {
                                                //檢查物料批號是否重複
                                                if(!checkMaterialDouble(dialog.tmpLotNo, dialog.materialsInfo)){
                                                    var content = {
                                                        wo_no:dialog.wo_no,
                                                        materials_lot_no: dialog.tmpLotNo,
                                                        return_type:'1',
                                                        op_no: dialog.op_no
                                                    }
                                                    //檢查物料批號是否存在
                                                    $MMWService.sendToServer({
                                                        uri: 'ServicesSTD.Module_MAT.sub_release_part_info_get',
                                                        content : content,
                                                        success : function(data){
                                                            if(data.sub_release_part_info_get.length>0){
                                                                dialog.materialsInfo.push({
                                                                    materials_no: data.sub_release_part_info_get[0].materials_no,
                                                                    materials_lot_no: dialog.tmpLotNo,
                                                                    qty: dialog.tmpQty,
                                                                });
                                                                dialog.tmpLotNo='';//清空物料批號
                                                                dialog.tmpQty= 0;//數量歸0
                                                            } else {
                                                                $rootScope.showAlert($filter('translate')('B0204.msg.materialNotFound'));
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    $rootScope.showAlert($filter('translate')('B0204.msg.materials_lot_no_double'));
                                                }
                                            }
                                        }

                                    },
                                    selectAll: function (isSelectAll) {
                                        // 20220318 add by Alan for M#153221: 增加全選功能
                                        dialog._isSelectAll = isSelectAll;
                                        dialog.materialsInfo = dialog.materialsInfo.map((item) => {
                                            item._isSelect = dialog._isSelectAll;
                                            return item;
                                        });
                                    },
                                    select: function (event, index, item) {
                                        item._isSelect = !item._isSelect;
                                    },
                                    back: function () {
                                        this.hide();
                                    },
                                    confirm: function () {
                                        // 20220318 modify by Alan for M#153221: 重構上料檢核邏輯
                                        const materials_detail = dialog.materialsInfo
                                            .filter((item) => item.isSelect == true)
                                            .map((item) => ({
                                                wo_no: dialog.wo_no,
                                                materials_no: item.materials_no,
                                                materials_lot_no: item.materials_lot_no,
                                                qty: item.qty
                                            }));

                                        if (materials_detail.length <= 0) {
                                            $rootScope.showAlert($filter('translate')('B0204.showAlert.column3'));
                                            return
                                        }

                                        // 20210111 add FOR #78842
                                        if (dialog.show_flag) {
                                            const inputLotNoList = materials_detail.filter(item => item.inputLotNo != '' && item.inputLotNo != undefined);
                                            if (inputLotNoList.length == 0) {
                                                $rootScope.showAlert($filter('translate')('B0204.msg.materials_lot_no_not_empty'));
                                                return;
                                            }
                                        } else {
                                            const isZero = materials_detail.some((item) => item.qty == 0);
                                            if (isZero) {
                                                $rootScope.showAlert($filter('translate')('B0204.msg.isZero'));
                                                return
                                            }
                                        }
                                        
                                        var content = {
                                            report_datetime: new Date(),
                                            machine_no: dialog.machine_no,
                                            op_no: dialog.op_no,
                                            materials_detail: materials_detail
                                        };
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_MAT.set_materials_to_materials_process',
                                            content: content,
                                            success: function (data) {
                                                $rootScope.showToast($filter('translate')('B0204.msg.saveSuccess'));
                                                dialog.hide();
                                                if (feedback)
                                                    feedback();
                                            }
                                        });
                                    },
                                    _fn: {
                                        confirm: {
                                            click: () => dialog.confirm(),
                                        }
                                    },
                                    _event:{
                                        payMaterialsNo: {
                                            change: (page_no, args) => {
                                                if(args.event.keyCode == 13){
                                                    sub_release_part_info_get(dialog);
                                                }
                                            },
                                            click: (page_no, event) => {
                                                dialog.loadMaterialCodeList();
                                            }
                                        }
                                    }
                                };
                            }
                        );
                    })
                }

                // 20210107 add FOR #78842
                function getDefaultStdFeeding() {
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_MAT.default_std_feeding_get',
                        content : {},
                        success : function(data){
                           showFlag = data.defaultStdFeeding == '0' ? true : false;
                           openDialog();
                        }
                    });
                };

                getDefaultStdFeeding();

            };
        }]);
});
